package week2nd;

public class IntNodeList {
    private IntNode list;

    public IntNodeList() {
        list = null;
    }

    public void add(int n) {
        IntNode node = new IntNode(n);
        IntNode current;

        if (list == null) {
            list = node;
        }
        else {
            current = list;
            while (current.next != null) {
                current = current.next;
            }
            current.next = node;
        }
    }

    public void insert(int index, int n) {
        IntNode node = list;
        int i = 0;
        while (node != null && i < index - 2) {
            node = node.next;
            i++;
        }
        IntNode sert = new IntNode(n);
        sert.next = node.next;
        node.next = sert;

        if (index == 1) {
            int temp = list.anInt;
            list.anInt = list.next.anInt;
            list.next.anInt = temp;
        }
    }

    public void delete(int n) {
        IntNode node = list;
        while (node.next.anInt != n) {
            node = node.next;
        }
        node.next = node.next.next;
    }

    @Override
    public String toString() {
        String result = "";

        IntNode current = list;

        while (current != null) {
            result += current.anInt + " ";
            current = current.next;
        }

        return result;
    }

    public void Sort() {
        int temp;
        if (list.anInt > list.next.anInt) {
            temp = list.next.anInt;
            list.next.anInt = list.anInt;
            list.anInt = temp;
        }
        IntNode temp1 = list;
        IntNode temp2;

        while (temp1.next != null) {
            temp2 = temp1.next;
            while (temp2.next != null) {
                if (temp1.next.anInt > temp2.next.anInt) {
                    temp = temp2.next.anInt;
                    temp2.next.anInt = temp1.next.anInt;
                    temp1.next.anInt = temp;
                }
                temp2 = temp2.next;
            }
            temp1 = temp1.next;
        }

    }

    private class IntNode {
        public int anInt;
        public IntNode next;

        //--------------------------------------------------------------
        //  Sets up the node
        //--------------------------------------------------------------
        public IntNode(int n) {
            anInt = n;
            next = null;

        }
    }

    public void HeadInsert(int n) {
        IntNode node = new IntNode(n);
        node.next = list;
        list = node;

    }
}
